<template>
  <!-- 支持多个根元素 -->
    <!-- 左上角人员方向 -->
     <div class="left_top_title"></div>
      <dv-border-box8  class="left_top" :dur="5">
        <t-chart
          v-if="leftTopOptions.series[0].data.length"
          :options="leftTopOptions"
          :theme="isDark"
          :isEmpty="isEmptyFn"
          @click="click"
          @chart="chart"
          >
        </t-chart>
    </dv-border-box8>
<!-- 中间地图 -->
    <dv-border-box8 class="center_top" :dur="5">
      <t-chart
          v-if="centerMapOptions.series[0].data.length"
          :ifMap="true"
          :options="centerMapOptions"
          :theme="isDark"
          :isEmpty="isEmptyFn"
          @click="click"
          @chart="chart"
          >
        </t-chart>


    </dv-border-box8>
    <div class="right_top_title"></div>
      <dv-border-box8  class="right_top" :dur="5">
        <t-chart
          v-if="rightTopOptions.series[0].data.length"
          :options="rightTopOptions"
          :theme="isDark"
          :isEmpty="RightIsEmptyFn"
          @click="click"
          @chart="chart"
          >
          <div class="button_container">

            <button class="button" @click="changeEx(1)">设计</button>
            <button class="button" @click="changeEx(2)">vr</button>
            <button class="button" @click="changeEx(3)">鸿蒙</button>
          </div>

        </t-chart>
    </dv-border-box8>

    <div class="right_bottom_title"></div>
      <dv-border-box8  class="right_bottom" :dur="5">
        <t-chart
          v-if="rightBottomOptions.series[0].data.length"
          :options="rightBottomOptions"
          :theme="isDark"
          :isEmpty="RightIsEmptyFn"
          @click="click"
          @chart="chart"
          >
        </t-chart>
    </dv-border-box8>
  </template>

<script setup >
import { reactive, ref} from 'vue'
import TChart from '../../components/TCharts.vue'
import {leftTopOption,righTopOption,centerMapOption,rightBottomOption} from "./echartsData"
import {getByAreaCode,getStuDistribution,getStuStatsSalary} from "@/apis/jobDirection"
import  cityData from "@/assets/json/CityData.json"
import  citylatlng from "@/assets/json/citylatlng.json"

//============= 左上echarts图形 start=================
const chartRef = ref(null)
let leftTopOptions  =reactive(leftTopOption);
const isEmptyFn = (options) => {
  return options.series[0].data.length === 0
}
const RightIsEmptyFn = (options) => {
  return options.series[0].data.length === 0
}
// 获取近三年毕业生流向数据 
const handlegetByAreaCode = function(){
  getByAreaCode().then((res)=>{
    // 1后端返回的数据里面的workCity 变成汉字
    let resultData = res.data.data.result.map((item)=>{
      return {...item,workCityName:getCityLabelByCode(item.workCity)}
    })

   const newResultData= transformData(resultData)
    console.log("返回的数据",newResultData)
    leftTopOptions.legend.data= newResultData.legendYearData.map((item)=>{return item.toString()});  //["2024", "2023"]
    leftTopOptions.yAxis.data  =newResultData.yAxisData;  //["南京","上海","北京"]
    leftTopOptions.series[0].data=newResultData.seriesData[0]  ;  //[12, 23, 35]
    leftTopOptions.series[1].data =newResultData.seriesData[1];
    leftTopOptions.series[2].data =newResultData.seriesData[2];
  })
}


handlegetByAreaCode()
const chart = (dom) => {
  chartRef.value = dom
}
//=========== 左上角echarts 逻辑处理 end===================
//=========== 右上角echarts 逻辑处理 end===================
const rightTopOptions = reactive(righTopOption)
const centerMapOptions = reactive(centerMapOption);

// 请求数据

const RightTopParams = reactive({
  expertiseId:1
})
const handleGetStuDistribution = async function(){
    let result = await getStuDistribution(RightTopParams)
    result= result.data.data.result.map((item)=>{
        return {value:item.total,name:getCityLabelByCode(item.workCity)}
      }).sort((a, b) => {
      return b.value - a.value;
    });
    console.log("result", result)
    // 得到数据后修改options的值
    rightTopOptions.yAxis[0].data = result.map((item)=>{return item.name})
    rightTopOptions.yAxis[1].data = result.map((item)=>{return item.name})
    rightTopOptions.series[0].data = result
    
// =======中间地图逻辑start======

// 1请求数据 返回的result数据得到每个城市对应 的经纬度坐标
let mapresult = result.map((item)=>{
  return {...item,latlng:getLatlngByName(item.name)}
})
console.log(JSON.stringify(mapresult) ,"mapresult")

// 2:根据数据组装echarts需要的活的数据格式
function transformData(data) {
    return data.map(item => {
        const [lat, lng] = item.latlng.split(',').map(Number);
        return {
            name: item.name,
            value: [lng, lat], // 注意：这里假设经度在前，纬度在后，根据需要调整
            itemStyle: { color: '#00EEFF' }
        };
    });
}
// 得到飞线数据
function transformLineData(data) {
    return data.map(item => {
        const [lat, lng] = item.latlng.split(',').map(Number);
        return {
            coords: [[117.21447,39.1208],[lng, lat]]
        };
    });
}
const pointsArr = transformData(mapresult)
const  lineDataArr= transformLineData(mapresult)
console.log(pointsArr,"pointitem",lineDataArr)

// 创建两个数组. pointsArr
// lineDataArr
// 3 修改options的值
centerMapOptions.series[0].data = pointsArr
centerMapOptions.series[1].data = lineDataArr

//  4步:提出成了公共的.setOptions 数据就变了
// 5公共的 调用resize


// =======中间地图逻辑end======




}
// 点击切换系室
const changeEx = (val)=>{
  RightTopParams.expertiseId = val
  handleGetStuDistribution()
}
handleGetStuDistribution()
//=========== 右上角echarts 逻辑处理 end===================
// ============右下角漏斗图 start================
// 1获取容器初始化一个echarts实例(获取到.mounted  抽离成公共的了)
// 2找到合适的options提取到外面去了
const rightBottomOptions =reactive(rightBottomOption) 
// 3请求数据.先去处理数据,变成数据结构和options的一样 修改options值
async function  handlegetStuStatsSalary(){
 const result = await getStuStatsSalary()
 const resultSeries= categorizeSalary(result.data.data.result)
 console.log("漏斗图数据",resultSeries);
 rightBottomOptions.series[0].data =resultSeries.series0
 rightBottomOptions.series[1].data =resultSeries.series1

}
handlegetStuStatsSalary();
// 4.调用setOptions方法 (抽离成公共的了)====图形就发生变化了
// (实例在封装的组件里面里面.setOptions也抽离出去了...深度监听了.options的改变)
// 5.echarts适配屏幕调用resize方法. 离开时候.销毁监听.销毁实例


// ============右下角漏斗图 end================

//漏斗图数据处理
function categorizeSalary(data) {
  const salaryRanges = [
    { name: "30K+", min: 30000 },
    { name: "20K~30K", min: 20000 },
    { name: "15K~20K", min: 15000 },
    { name: "10K~15K", min: 10000 },
    { name: "10K以下", min: 0 }
  ];
 
  let series1 = salaryRanges.map(range => ({ name: range.name, value: 0 }));
 
  data.forEach(item => {
    let rangeIndex;
    for (let i = 0; i < salaryRanges.length; i++) {
      if (item.salary >= salaryRanges[i].min) {
        rangeIndex = i;
        break;
      }
    }
 
    if (rangeIndex !== undefined) {
      series1[rangeIndex].value += item.total;
    }
  });
 
  const totalSum = series1.reduce((sum, item) => sum + item.value, 0);
  const series0 = series1.map(item => ({ ...item, value: totalSum }));
 
  return { series0, series1 };
}


// 通过传入城市代码.获取城市名称
function getCityLabelByCode(code) {
    // Function to recursively search for the city with the specified code
    function searchCity(data) {
        for (let item of data) {
            if (item.code === code) {
                return item.label;
            }
            if (item.children && item.children.length > 0) {
                let result = searchCity(item.children);
                if (result) {
                    return result;
                }
            }
        }
        return null;
    }
 
    // Start the search from the root of the national data structure
    return searchCity(cityData);
}

// 通过传入城市名字获取城市经纬度
function getLatlngByName(name){
  let currentLat = ""
   citylatlng.filter((item)=>{
    if(item.name.startsWith(name)) {
      currentLat= item.latlng
    }
  })
  return currentLat
}

// 左上角数据格式化
function transformData(data) {
    // 提取所有唯一的年份并排序
    const legendYearData = [...new Set(data.map(item => item.gradYear))].sort((a, b) => b - a);
 
    // 提取所有唯一的城市名称并排序
    const yAxisData = [...new Set(data.map(item => item.workCityName))].sort();
 
    // 构建seriesData
    const seriesData = legendYearData.map(year => {
        // 对于每个年份，创建一个数组来存储对应城市的total值
        return yAxisData.map(city => {
            // 查找该年份和该城市的数据
            const item = data.find(d => d.gradYear === year && d.workCityName === city);
            // 返回total值，如果没有找到则返回0（或者根据需求处理）
            return item ? item.total : 0;
        });
    });
 
    // 返回最终的对象
    return {
        legendYearData: legendYearData,
        yAxisData: yAxisData,
        seriesData: seriesData
    };
}
 

</script>
<style lang='scss' scoped>
.left_top_title{
  background: url('../../assets/images/left_title@2x.png') no-repeat 100% 100%;
  width: 450px;
  height: 40px;
}
.left_top{
  width: 450px;
  height: 50%;
  background: #0C1D5F;
}



.right_top_title{
  background: url('../../assets/images/right_title@2x.png') no-repeat;
  background-size: 100% 100%;
  width: 453px;
  height: 42px;
  position:absolute;
  right:0px;
  top:0;
}
.right_top,.right_bottom{
  width: 450px;
  background: #0C1D5F;
  position:absolute;
  right:0px;
  // top:40px;
  // border:1px solid red;
}
.right_top{
  height: 374px;
  top: 40px;
}
.right_bottom{
  height: 359px;
  top: 66%;
}
.button_container{
  display: flex;
  justify-content: space-around;
  flex: 1;
  padding: 15px 0 0 0;
}
.button{
  appearance: none;
  border: none;
  outline: none;
  background: #0ebdf8;
  text-align: center;
  color: aliceblue;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  width: 80px;
  height: 35px;
  font-size: 16px;
}
.center_top{
  position: absolute;
  left:550px;
  top: 0px;
  width: 700px;
  height: 500px;
}
.right_bottom_title{
  background: url('../../assets/images/right_title@2x.png') no-repeat;
  background-size: 100% 100%;
  width: 453px;
  height: 42px;
  position:absolute;
  right:0px;
  top:60%;
}
</style>